/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @see https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
  if(!nums.length) {
    return null;
  }
  let len = nums.length;
  let mid = Math.ceil((len - 1) / 2);
  // 构造二叉树
  let root = new treeNode(nums[mid]);
  let left = nums.slice(0, mid);
  let right = nums.slice(mid +1);
  root.left = sortedArrayToBST(left);
  root.right = sortedArrayToBST(right);
  return root;
};

function treeNode(val, left, right) {
  this.val = val;
  this.left = left || null;
  this.right = right || null;
}

console.log(sortedArrayToBST([-10,-3,0,5,9,20]));